package org.alex.nettychat.netty.custom.handler;


import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import org.alex.nettychat.netty.custom.protocol.CreateGroupRequestPacket;
import org.alex.nettychat.netty.custom.protocol.CreateGroupResponsePacket;
import org.alex.nettychat.netty.custom.utils.SessionUtil;

import java.util.ArrayList;
import java.util.List;


/**
 * 创建群里请求
 *
 * @author : alex
 */
public class CreateGroupRequestHandler extends SimpleChannelInboundHandler<CreateGroupRequestPacket> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, CreateGroupRequestPacket createGroupRequestPacket) throws Exception {
        List<Integer> userIdList = createGroupRequestPacket.getUserIdList();

        List<String> userNameList = new ArrayList<>();
        // 创建一个channel分组
        ChannelGroup channelGroup = new DefaultChannelGroup(ctx.executor());

        // 筛选出加入群聊的用户channel和name
        for (Integer userId : userIdList) {
            Channel channel = SessionUtil.getChannel(userId);
            if (channel != null) {
                channelGroup.add(channel);
            }

            userNameList.add(SessionUtil.getSession(channel).getUserName());
        }

        // 创建结果响应
        CreateGroupResponsePacket createGroupResponsePacket = new CreateGroupResponsePacket();

        createGroupResponsePacket.setSuccess(true);
        createGroupResponsePacket.setGroupId(1);
        createGroupResponsePacket.setUserNameList(userNameList);
        SessionUtil.saveChannelGroup(createGroupResponsePacket.getGroupId(), channelGroup);
        // 向每个客户端发送结果通知
        channelGroup.writeAndFlush(createGroupResponsePacket);

        System.out.println("群创建成功，Id:" + createGroupResponsePacket.getGroupId() +
                ", 成员：" + userNameList.toString());
    }
}
